//index.js
//import initComputed from 'wx-computed'
// 手动引入
import initComputed from '../../lib/wxComputed.min'
var myDate = new Date()
const app = getApp()
const watch = require('../../utils/util.js')
Page({
  data: {
    payinfo: {},
    pay1: {
      'nonceStr': "11"
    },
    //发送支付请求参数
    nonceStr: "",
    package: "",
    paySign: "",
    timeStamp: "",
    appId: "",

    string: "",
    //签名
    sign: "",
    // excel下载链接
    fileUrl: "",
    flag: true,
    //学校
    school: ['郑州市郑东新区美秀小学', '洛阳市洛龙区古城小学'],
    // 年级
    grade: [],
    // 班级
    class: [],
    // 身高
    height: [],
    weight: [],
    // 腰围
    waist: [],
    // 规格
    specifications: ['郑州市郑东新区美秀小学', '洛阳市洛龙区古城中学'],
    index: "",
    // 数量
    numbers: [],
    //单个货款
    single_money: '',
    single_moneys: [],
    // 性别
    sex: ['男', '女'],
    // 提交信息
    info: {
      school: "",
      // 登陆码
      login_code: "",
      grade: "1",
      class: "1",
      height: "120",
      weight: "30",
      waist: "30",
      // 规格
      specifications: "",
      // sex: "",
      // 姓名
      name: "",
      // 电话
      tele: "",
      //件数
      number: 1,
      // 货款总额
      total_money: "",
    },
    // 更新的古城中学单价
    updateGczx: '',
    // 更新的美秀小学单价
    updateMxxx: '',
  },
  // 年级选择
  bindChange4(e) {
    const val = e.detail.value
    // console.log(this.data.height[val[1]])
    const tem = this.data.grade[val]
    this.setData({
      ['info.grade']: tem
    })
    console.log(this.data.info.grade)
  },
  // 班级选择
  bindChange5(e) {
    const val = e.detail.value
    // console.log(this.data.height[val[1]])
    const tem = this.data.class[val]
    this.setData({
      ['info.class']: tem
    })
    console.log(this.data.info.class)
  },
  // 身高选择
  bindChange(e) {
    const val = e.detail.value
    // console.log(this.data.height[val[1]])
    const tem = this.data.height[val]
    this.setData({
      ['info.height']: tem
    })
    console.log(this.data.info.height)
  },
  // 体重选择
  bindChange1(e) {
    const val = e.detail.value
    // console.log(this.data.height[val[1]])
    const tem = this.data.weight[val]
    this.setData({
      ['info.weight']: tem
    })
    console.log(this.data.info.weight)
  },
  // 腰围选择
  bindChange2(e) {
    const val = e.detail.value
    // console.log(this.data.height[val[1]])
    const tem = this.data.waist[val]
    this.setData({
      ['info.waist']: tem
    })
    console.log(this.data.info.waist)
  },
  // 数量选择
  bindChange3(e) {
    const val = e.detail.value
    console.log(this.data.height[val])
    const tem = this.data.numbers[val]
    this.setData({
      ['info.number']: tem
    })
    console.log(this.data.info.number)
  },

  // 导出excel
  async dowload() {
    wx.showToast({
      title: '请稍等',
      icon: 'none',
      duration: 1500,
    })
    let data;
    let _this = this
    await wx.cloud.callFunction({
      name: 'getThings'
    }).then(res => {
      // console.log(res)
      data = res.result.data
    })
    //console.log(data)
    wx.cloud.callFunction({
      name: 'excel',
      data: {
        userdata: data
      }
    }).then(res => {
      console.log(res)
      _this.getFileUrl(res.result.fileID)
    }).catch(err => {
      console.log(err)
    })
  },

  //获取云存储文件下载地址，这个地址有效期一天
  getFileUrl(fileID) {
    let that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        // get temp file URL
        console.log("文件下载链接", res.fileList[0].tempFileURL)
        that.setData({
          fileUrl: res.fileList[0].tempFileURL
        })
      },
      fail: err => {
        // handle error
        console.log("a")
        console.log(err)
      }
    })
  },
  //复制excel文件下载链接
  copyFileUrl() {
    let that = this
    wx.setClipboardData({
      data: that.data.fileUrl,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log("复制成功", res.data) // data
          }
        })
      }
    })
  },

  // 删除后台订购信息
  deleteInfo() {
    wx.showModal({
      title: '此操作将删除后台所有订购信息且无法恢复',
      content: '是否确认',
      success(res) {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'delete'
          }).then(res => {
            console.log(res)
            wx.showToast({
              title: '删除成功',
              icon: 'none',
              duration: 1500,
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 监视应付货款
  watch: {
    'sign': function (newValue, oldValue) {
      console.log(newValue, oldValue); //newValue : true , oldValue : false
    },
  },

  //计算属性总价格
  computed: {
    // 这是一个函数，返回值为此计算属性的值
    total() {
      let tot = this.data.single_money * this.data.info.number
      if (tot > 0 && tot < 9999999) {
        this.data.info.total_money = tot
        return tot
      } else
        return 0
    },
  },
  // 页面加载
  onLoad: function () {
    // 设置数据监听器
    watch.setWatcher(this);
    // 执行computed属性初始化
    initComputed(this)

    let arr = []
    for (let i = 120; i < 210; i++) {
      arr.push(i)
    }
    // 设置身高范围
    this.setData({
      height: arr
    })
    arr = []
    for (let i = 30; i < 120; i++) {
      arr.push(i)
    }
    // 设置体重和腰围范围
    this.setData({
      weight: arr,
      waist: arr
    })
    arr = []
    for (let i = 1; i < 200; i++) {
      arr.push(i)
    }
    // 设置购买数量范围
    this.setData({
      numbers: arr
    })
    arr = []
    for (let i = 1; i <= 9; i++) {
      arr.push(i);
    }
    // 设置年级范围
    this.setData({
      grade: arr
    })
    arr = []
    for (let i = 1; i <= 18; i++) {
      arr.push(i);
    }
    // 设置班级范围
    this.setData({
      class: arr
    })
    const db = wx.cloud.database()
    let that = this
    const _ = db.command
    let _this = this
    let num = []
    for (let i = 1; i <= 200; i++) {
      num.push(i)
    }
    this.setData({
      numbers: num
    })
    db.collection('price').where({
        mxxx: _.exists(true)
      })
      .get({
        success: function (res) {
          // res.data 是包含以上定义的两条记录的数组
          console.log(res.data)
          that.data.single_moneys.push(res.data[0].mxxx)
          that.data.single_moneys.push(res.data[0].gczx)
          //console.log(that.data.single_money)
          //console.log(res)
          let mxxx = res.data[0].mxxx
          let gczx = res.data[0].gczx
          wx.getStorage({
            // school: school,
            //         login_code: login_code,
            //         flag:true,
            key: "key",
            success: (res) => {
              console.log(res)
              //var id = res.data;  // 这里获取到的id值即为A页面传递id值
              _this.setData({
                ['info.school']: res.data.school,
                ['info.login_code']: res.data.login_code,
                flag: res.data.flag
              })
              if (res.data.school == "郑州市郑东新区美秀小学") {
                _this.setData({
                  ['info.specifications']: '郑州市郑东新区美秀小学',
                  single_money: mxxx
                })
              } else {
                _this.setData({
                  ['info.specifications']: '洛阳市洛龙区古城中学',
                  single_money: gczx
                })
              }
            },
            fail: () => {

            },
          });
        }
      })


  },

  // 支付
  async pay() {
    // wx.requestPayment({
    //   nonceStr: 'nonceStr',
    //   package: 'package',
    //   paySign: 'paySign',
    //   timeStamp: 'timeStamp',
    // }).then(res=> {
    //   console.log("aa")
    // })
    //this.data.info.grade == "" || this.data.info.class == "" || this.data.info.sex == "" ||
    if (this.data.info.height == "" || this.data.info.weight == "" || this.data.info.waist == "" || this.data.info.specifications == "" || this.data.info.number == "" || this.data.info.name == "" || this.data.info.tele == "")
      return wx.showToast({
        title: '请填写全部选项',
        icon: 'none',
        duration: 1500,
      })

    let openId;
    const db = wx.cloud.database()
    // db.collection('info').get()
    // .then(res => {
    //   console.log(res)
    // })
    let that = this //不要漏了这句，很重要
    let _this = this
    wx.cloud.callFunction({
      name: "getInfo"
    })
    await wx.cloud.callFunction({
      name: 'login',
    }).then(res => {
      //console.log(res)//res就将appid和openid返回了
      //做一些后续操作，不用考虑代码的异步执行问题。
      openId = res.result.openid
      // console.log(openId)
    })
    console.log(openId)
    await this.getSign(openId, this.data.info.total_money)
  },

  // 获取加密后的sign
  async getSign(openId, total_monoey) {
    let _this = this
    const db = wx.cloud.database()
    var myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth() + 1;
    let day = myDate.getDate();
    let hour = myDate.getHours();
    if (hour < 10) hour = "0" + hour
    let minutes = myDate.getMinutes();
    if (minutes < 10) minutes = "0" + minutes;
    let seconds = myDate.getSeconds();
    if (seconds < 10) seconds = "0" + seconds
    let time = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds
    wx.request({
      url: 'https://www.fashion-xf.online/get/sign/' + openId + "/" + total_monoey*100,
      method: 'get',
      success: function (res) {
        var order_number = res.data.data.trxid
        console.log(res.data.data)
        // let payinfo = res.data.data.payinfo;
        _this.setData({
          payinfo: JSON.parse(res.data.data.payinfo)
        })
        wx.requestPayment({
          nonceStr: _this.data.payinfo.nonceStr,
          package: _this.data.payinfo.package,
          paySign: _this.data.payinfo.paySign,
          timeStamp: _this.data.payinfo.timeStamp,
          signType: _this.data.payinfo.signType,
          appId: _this.data.payinfo.appId,
          success: function (res) {
            console.log(res)
            db.collection('menu').add({
                // data 字段表示需新增的 JSON 数据
                data: {
                  // 订单编号
                  order_number: order_number,
                  school: _this.data.info.school,
                  grade: _this.data.info.grade,
                  class: _this.data.info.class,
                  height: _this.data.info.height,
                  weight: _this.data.info.weight,
                  waist: _this.data.info.waist,
                  specifications: _this.data.info.specifications,
                  // sex: _this.data.info.sex,
                  // 登陆码
                  login_code: _this.data.info.login_code,
                  // 姓名
                  name: _this.data.info.name,
                  // 电话
                  tele: _this.data.info.tele,
                  //单个货款
                  single_money: _this.data.info.school,
                  //订购数量
                  number: _this.data.info.number,
                  // 货款总额
                  total_money: _this.data.info.total_money,
                  // 付款时间
                  time: time
                }
              })
              .then(res => {
                wx.showToast({
                  title: '付款成功',
                  icon: 'none',
                  duration: 1500,
                })
              })

              // 向用户表中添加
              db.collection('user_menu').add({
                // data 字段表示需新增的 JSON 数据
                data: {
                  // 订单编号
                  order_number: order_number,
                  school: _this.data.info.school,
                  grade: _this.data.info.grade,
                  class: _this.data.info.class,
                  height: _this.data.info.height,
                  weight: _this.data.info.weight,
                  waist: _this.data.info.waist,
                  specifications: _this.data.info.specifications,
                  // sex: _this.data.info.sex,
                  // 登陆码
                  login_code: _this.data.info.login_code,
                  // 姓名
                  name: _this.data.info.name,
                  // 电话
                  tele: _this.data.info.tele,
                  //单个货款
                  single_money: _this.data.info.school,
                  //订购数量
                  number: _this.data.info.number,
                  // 货款总额
                  total_money: _this.data.info.total_money,
                  // 付款时间
                  time: time
                }
              })
          },
          fail: function (err) {
            console.log(err)
          }
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

  // 退出
  // logout(e) {
  //   // wx.clearStorageSync('key');
  //   wx.redirectTo({

  //     url: '/pages/login/index',
  //   })
  // },

  // 获取班级
  getClass(e) {
    var value = e.detail.value
    this.setData({
      ['info.class']: value
    })
  },

  // 获取订购数量
  getSpecifications(e) {
    var value = e.detail.value
    this.setData({
      ['info.number']: value
    })
  },

  // 获取姓名
  getName(e) {
    var value = e.detail.value
    this.setData({
      ['info.name']: value
    })
  },

  // 获取手机号
  getTele(e) {
    var value = e.detail.value
    this.setData({
      ['info.tele']: value
    })
  },

  // 修改古城中学单价
  updateGczx(e) {
    if (this.data.updateGczx == "")
      return wx.showToast({
        title: '价格不能为空',
        icon: 'none',
        duration: 2000
      })
    const db = wx.cloud.database()
    const _ = db.command
    let _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认修改',
      success(res) {
        if (res.confirm) {
          db.collection('price').where({
            gczx: _.exists(true)
          }).update({
            // data 传入需要局部更新的数据
            data: {
              // 表示将 done 字段置为 true
              gczx: _this.data.updateGczx
            },
            success: function (res) {
              console.log(res)
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 2000
              })
            },
            fail: function (err) {
              console.log(err)
              wx.showToast({
                title: '修改失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '取消修改',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 修改古城中学单价
  updateMxxx(e) {
    if (this.data.updateMxxx == "")
      return wx.showToast({
        title: '价格不能为空',
        icon: 'none',
        duration: 2000
      })
    const db = wx.cloud.database()
    const _ = db.command
    let _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认修改',
      success(res) {
        if (res.confirm) {
          db.collection('price').where({
            gczx: _.exists(true)
          }).update({
            // data 传入需要局部更新的数据
            data: {
              // 表示将 done 字段置为 true
              mxxx: _this.data.updateMxxx
            },
            success: function (res) {
              console.log(res)
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 2000
              })
            },
            fail: function (err) {
              console.log(err)
              wx.showToast({
                title: '修改失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '取消修改',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 
  bindKeyInputGczx: function (e) {
    this.setData({
      updateGczx: e.detail.value
    })
    console.log(this.data.updateGczx)
  },
  bindKeyInputMxxx: function (e) {
    this.setData({
      updateMxxx: e.detail.value
    })
    console.log(this.data.updateMxxx)
  },

  // 学校信息
  bindPickerChange1: function (e) {
    //console.log(e)
    //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
    let tem = this.data.school[e.detail.value]
    this.setData({
      ['info.school']: tem
    })


    //console.log(this.data.index)
  },

  // 身高信息
  // bindPickerChange2: function (e) {
  //   //console.log(e)
  //   //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
  //   let tem = this.data.grade[e.detail.value]
  //   this.setData({
  //     ['info.grade']: tem
  //   })
  //   //console.log(this.data.index)
  // },

  // 班级信息
  // bindPickerChange3: function (e) {
  //   //console.log(e)
  //   //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
  //   let tem = this.data.class[e.detail.value]
  //   this.setData({
  //     ['info.class']: tem
  //   })
  //   //9console.log(this.data.index)
  // },

  // 身高信息
  bindPickerChange4: function (e) {
    //console.log(e)
    //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
    let tem = this.data.height[e.detail.value]
    this.setData({
      ['info.height']: tem
    })
    //console.log(this.data.index)
  },

  //体重信息
  bindPickerChange5: function (e) {
    //console.log(e)
    //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
    let tem = this.data.weight[e.detail.value]
    this.setData({
      ['info.weight']: tem
    })
    //console.log(this.data.index)
  },

  // 腰围
  bindPickerChange6: function (e) {
    //console.log(e)
    //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
    let tem = this.data.waist[e.detail.value]
    this.setData({
      ['info.waist']: tem
    })
    //console.log(this.data.index)
  },

  // 规格信息
  bindPickerChange7: function (e) {
    //console.log(e)
    //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
    let tem = this.data.specifications[e.detail.value]
    this.setData({
      index: e.detail.value,
      ['info.specifications']: tem,
    })
    console.log(this.data.info.specifications)
  },

  // 性别选择
  // bindPickerChange8: function (e) {
  //   //console.log(e)
  //   //console.log('picker发送选择改变，携带值为', this.data.array[e.detail.value])
  //   let tem = this.data.sex[e.detail.value]
  //   this.setData({
  //     ['info.sex']: tem
  //   })
  //   //console.log(this.data.index)
  // },
  // 数量选择
  bindPickerChange9: function (e) {
    let tem = this.data.numbers[e.detail.value]
    this.setData({
      ['info.number']: tem
    })
    //console.log(this.data.info.number)
  },
})